﻿using System;
using System.IO;
using System.Web;

namespace PrintService
{
    public class WriteFileHttpServer : HttpServer
    {
        public WriteFileHttpServer(int port)
            : base(port) {
        }
        public override void handleGETRequest(HttpProcessor p, string http_url)
        {
            var queryStrings = HttpUtility.ParseQueryString(http_url);
            var callBack = queryStrings.Get("callback");
            var responseString = string.Empty;
            try
            {
                var content = queryStrings.Get("content");
                var templateName = queryStrings.Get("templateName");
                if (string.IsNullOrEmpty(content) || string.IsNullOrEmpty(templateName))
                {
                    LogHelper.LogHttpInfo("parameters is not correct, please revise them and try again");
                    throw new Exception("参数不不正确，请核对后重试");
                }

                //创建打印数据源文件
                var filePath = Path.Combine(ServiceConstants.DataFolder, $"{templateName}_{DateTime.Now.ToString("yyyyMMddHHmmssffffff")}.txt");
                if (PrintHelper.SaveDataAsFile(content, filePath))
                {
                    var printResult = PrintHelper.DoPrint(filePath, templateName);
                    var isSuccess = string.IsNullOrEmpty(printResult);
                    var msg = isSuccess ? "打印成功" : printResult;
                    responseString = "{\"success\":\"" + isSuccess.ToString().ToLower() + "\",\"message\":\"" + msg + "\"}";
                }
            }
            catch (Exception e)
            {
                responseString = callBack + "({\"success\":\"false\",\"message\":\"" + e.Message + "\"})";
            }
            p.writeSuccess(responseString);
        }

        public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData)
        {
            Console.WriteLine("POST request: {0}", p.http_url);
            string data = inputData.ReadToEnd();

            p.writeSuccess("handlde post request success");
            p.outputStream.WriteLine("<html><body><h1>test server</h1>");
            p.outputStream.WriteLine("<a href=/test>return</a><p>");
            p.outputStream.WriteLine("postbody: <pre>{0}</pre>", data);            
        }
    }
}
